import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入token
import { getToken } from '@/utils/localStorage'

// 导入toast
import { Toast } from 'vant'
// 导入二级路由
const Article = () => import('@/views/Article')
const Collect = () => import('@/views/Collect')
const Like = () => import('@/views/Like')
const User = () => import('@/views/User')
// 导入一级路由
// import Detail from '@/views/Detail'
// import Layout from '@/views/Layout'
// import Login from '@/views/Login'
// import Register from '@/views/Register'
const Detail = () => import('@/views/Detail')
const Layout = () => import('@/views/Layout')
const Login = () => import('@/views/Login')
const Register = () => import('@/views/Register')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/article/:id', component: Detail },
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [
        { path: '/article', component: Article },
        { path: '/collect', component: Collect },
        { path: '/like', component: Like },
        { path: '/user', component: User }
      ]
    },
    { path: '/login', component: Login },
    { path: '/register', component: Register }
  ]
})

// 白名单
const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  if (getToken()) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      Toast.fail('请先登录')
      next('/login')
    }
  }
})

export default router
